package random

import (
	"google.golang.org/grpc/balancer"
	"google.golang.org/grpc/balancer/base"
	"google.golang.org/grpc/resolver"
	"log"
	"math/rand"
)

type Builder struct {
}

func (b *Builder) Build(info base.PickerBuildInfo) balancer.Picker {
	connList := make([]*Conn, 0, len(info.ReadySCs))
	for subConn, sc := range info.ReadySCs {
		connList = append(connList, &Conn{
			conn: subConn,
			addr: sc.Address,
		})
	}

	bl := &Balancer{
		connList: connList,
		len:      len(connList),
	}

	return bl
}

type Balancer struct {
	connList []*Conn
	len      int
}

func (b *Balancer) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
	if len(b.connList) == 0 {
		return balancer.PickResult{}, balancer.ErrNoSubConnAvailable
	}
	// 随机 [0, len(b.connList)
	idx := rand.Intn(len(b.connList))

	return balancer.PickResult{
		SubConn: b.connList[idx].conn,
		Done: func(info balancer.DoneInfo) {

			if info.Err != nil {
				log.Println(info.Err)
				return
			}
		},
	}, nil
}

type Conn struct {
	conn balancer.SubConn
	addr resolver.Address
}
